<?php
/*
Plugin Name: Pidgin Lifestream Feed
Plugin URI:  http://code.google.com/p/pidgin-lifestream/
Description: RSS for Pidgin status messages and the Wordpress Lifetream plugin
Version: 0.1
Author: Jim Hribar
Author URI: http://www.jimhribar.com
*/

function pidgin_lifestream_install()
{
    global $wpdb;
    $table = $wpdb->prefix."lifestream_pidgin";
    $structure = "CREATE TABLE IF NOT EXISTS $table (
      			title varchar(1024) default NULL,
        		link varchar(1024) default NULL,
				description varchar(1024) default NULL,
	    		author varchar(1024) default NULL,
	      		category varchar(1024) default NULL,
	        	comments varchar(1024) default NULL,
				enclosure varchar(1024) default NULL,
		    	guid varchar(1024) default NULL,
		      	pubdate datetime default NULL,
		        source varchar(1024) default NULL
			);";
    $wpdb->query($structure);	
}

register_activation_hook(__FILE__,'pidgin_lifestream_install');

$protocol = $_GET['protocol'];
$username = $_GET['username'];
$message = $_GET['message'];

if(isset($protocol) && isset($username) && isset($message))
{
	$wpdb->query( $wpdb->prepare( "INSERT INTO " . $wpdb->prefix . "lifestream_pidgin ( category, author, title, pubdate ) VALUES ( %s, %s, %s, now() )", $protocol, $username, $message ) ); //string for date??
	exit;	
}
else if (isset($protocol))
{
    header("Content-Type: application/xml;");	
	$feed = $wpdb->get_results( $wpdb->prepare( "select category, author, title, DATE_FORMAT(pubdate,'%%a, %%d %%b %%Y %%T') AS pubdate from ". $wpdb->prefix. "lifestream_pidgin where category = %s order by pubdate desc", $protocol ) );	
	echo "<?xml version=\"1.0\" ?>\n";
	echo "<rss version=\"2.0\">\n";
	echo "<channel>\n";
	echo "<title>Pidgin Lifestream Feed</title>\n";
	echo "<link>http://www.jimhribar.com</link>\n";
	echo "<description>Status updates from Pidgin posted to a WordPress blog via RSS</description>\n";
    foreach($feed as $entry)
    {	
		echo "<item>\n";
        echo "<title>" . strip_tags($entry->title) . "</title>\n";
		//echo "<link>";
		echo "<description><![CDATA[" . $entry->title . "]]></description>\n";
		echo "<author>" . $entry->author . "</author>\n";
		echo "<category>" . $entry->category . "</category>\n";
		//echo "<comments>";
		//echo "<enclosure>";
		//echo "<guid>";
        echo "<pubDate>" . $entry->pubdate . " -0500</pubDate>\n";
		//echo "<source>";
        echo "</item>\n";				
    }
	echo "</channel>\n";
	echo "</rss>\n";
	exit;
}
?>